from repoze.who.plugins import auth_tkt
from pylons import config

class MyAuthTktCookiePlugin(auth_tkt.AuthTktCookiePlugin):

  def __init__(self, *args, **kwargs):
    self.SIGNOUT_PART = kwargs.pop('SIGNOUT_PART')
    super(MyAuthTktCookiePlugin, self).__init__(*args, **kwargs)

  def remember(self, environ, identity):
    if identity.get('delete_cookie'):
      return self.forget(environ, identity)
    return super(MyAuthTktCookiePlugin, self).remember(environ, identity)
  
  def identify(self, environ):
    path_info = environ['PATH_INFO']
    identity = super(MyAuthTktCookiePlugin, self).identify(environ)
    if path_info.endswith(self.SIGNOUT_PART) and identity is not None:
      identity['delete_cookie'] = True
    return identity

def _bool(value):
  if isinstance(value, basestring):
    return value.lower() in ('yes', 'true', '1')
  return value


def make_plugin(secret=None,
                cookie_name='auth', # XXX Useless ?!?
                secure=False, include_ip=False):
  if secret is None:
    raise ValueError('secret must not be None')
  try:
    SIGNOUT_PART = "%s" % config["pylons.g"].SIGNOUT_PART
  except:
    raise ValueError("The pylons.config dict must have the key 'SIGNOUT_PART'.")
  plugin = MyAuthTktCookiePlugin(secret, cookie_name,
                                 _bool(secure), _bool(include_ip),
                                 SIGNOUT_PART=SIGNOUT_PART)
  return plugin
